package com.example.demo.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.service.TokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
    @Value("${spring.token.secretKey}")
    private String secretKey;

    /**
     * 加密token.
     */
    public String getToken(String email, String hxPassword) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        return JWT
                .create()
                .withClaim("email", email)
                .withClaim("hxPassword", hxPassword)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(this.secretKey));
    }

    /**
     * 解析token.
     * {
     * <p>
     * <p>
     * "userId": "weizhong",
     * "userRole": "ROLE_ADMIN",
     * "timeStamp": "134143214"
     * }
     */
    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(this.secretKey)).build().verify(token);
        Claim userId = decodedjwt.getClaim("email");
        Claim userRole = decodedjwt.getClaim("hxPassword");
        Claim timeStamp = decodedjwt.getClaim("timeStamp");
        map.put("email", userId.asString());
        map.put("hxPassword", userRole.asString());
        map.put("timeStamp", timeStamp.asLong().toString());
        return map;
    }
}
